const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

//云函数入口函数
exports.main = async (event, context) => {

  const sid = event.sid;
  const volunteer = event.volunteer;
  const team = event.team;

  //判断该联系请求是否为首次联系（chat_msg中是否有会话记录）
  const isSid = await findSid(sid);
  let newSidResult = '';
  if(isSid==true){return {isSid:true}}
  else{
    newSidResult = await newSid(sid,volunteer,team);
  }
  if(newSidResult){
    return {isSid:true}
  }else{
    return {isSid:false}
  } 
}
async function findSid(sid){
  const res = await cloud.database().collection('chat_msg')
  .where({
    session_id: sid
  })
  .get();
  const len = res.data.length;
  if(len == 0) return false;
  else return true;
}
async function newSid(sid,volunteer,team){
  const db=cloud.database();
  const _=db.command;
    //在集合chat_msg中新增一条会话记录
    try{
    await db.collection('chat_msg')
    .add({
      data:{
        session_id: sid,
        msg_set: []
      }
    })
    //在集合all_user中的对应志愿者记录的mySession_ids数组中push一个新的会话对象
    //包含了会话号 和 团队的名字和头像
    await db.collection('all_user')
    .where({
      _openid:volunteer.openid
    })
    .update({
       data:{
          mySession_ids:_.push({
                        session_id: sid,
                        teamUserInfo: {avatarUrl:team.avatarUrl,nickName:team.nickName},
                        leaveTime:'',
                        leaveTimeST:'',
                        unReadNum:parseInt(0),
                        show: true
         })
       }
    })
     //在集合all_team中的对应项目的团队记录的mySession_ids数组中push一个新的会话对象
     //包含了会话号 和 志愿者的uerInfo
    await db.collection('all_team')
    .where({
       _openid: team.openid
    })
    .update({
       data:{mySession_ids:_.push({
                        session_id: sid,
                        vtUserInfo: {avatarUrl: volunteer.avatarUrl,nickName: volunteer.nickName},
                        leaveTime:'', 
                        leaveTimeST:'',
                        unReadNum:parseInt(0),
                        show: false
                  })
            }
    })

    return true;
  }catch(err){
    return false;
  }
}